package leetcode_core.leetcode_1;

import org.junit.Test;

import java.util.Stack;

public class Calculate {
    public int calculate(String s) {
        return helper(new StringBuilder(s));
    }

    private int helper(StringBuilder s){
        Stack<Integer> stack = new Stack<>();
        //记录算式中的数字
        int num = 0;
        //记录num前的符号,初始化为+
        char sign = '+';
        while(s.length()>0){
            char c = s.charAt(0);
            s = s.delete(0, 1);
            //如果是数字,就连续读取出来
            if(Character.isDigit(c)){
                num = 10*num + (c-'0');
            }
            //如果不是数字,就证明遇到了下一个符号
            //之前的数字和符号就要存进栈中
            //存栈这个操作 还要在字符串遍历结束之后再来一次
            if(c == '('){
                num = helper(s);
            }
            if((!Character.isDigit(c) && c!=' ') || s.length() == 0 ){
                int pre = 0;
                switch (sign){
                    case '+':
                        stack.push(num);break;
                    case '-':
                        stack.push(-num);break;
                    //只需要拿出前一个数字做对应的运算即可
                    case '*':
                        pre = stack.peek();stack.pop();
                        stack.push(pre*num);
                        break;
                    case '/':
                        pre = stack.peek();stack.pop();
                        stack.push(pre/num);
                        break;
                }
                //更新符号为当前符号,数字清零
                sign = c;
                num=0;
            }
            if(c == ')'){
                break;
            }
        }
        //将栈中的所有结果进行求和
        int res = 0;
        while (!stack.isEmpty()){
            res += stack.peek();
            stack.pop();
        }
        return res;
    }

    @Test
    public void test(){
        System.out.println(calculate("1+1"));
        System.out.println(calculate("2 - 1 + 2"));
        System.out.println(calculate("(1+(4+5+2)-3)+(6+8)"));
    }

}
